package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.Tags;
import com.gaohe.service.TagsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/tags")
@Slf4j
public class TagsController {
    @Autowired
    private TagsService tagsService;
    //标签分页查询
    @GetMapping("/page")
    public R page(@RequestParam int page,
                  @RequestParam int pageSize,
                  @RequestParam(required = false) String name){
        Page<Tags> tagsPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Tags> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name),Tags::getName,name);
        qw.orderByDesc(Tags::getUpdateTime);
        tagsService.page(tagsPage,qw);
        return R.success(tagsPage);
    }
    //新建标签
    @PostMapping
    public R save(@RequestBody Tags tags)
    {
        boolean save = tagsService.save(tags);
        return save?R.success("新增成功"):R.error("新增失败");
    }
    //修改标签
    //回显
    @GetMapping("/{id}")
    public R findByID(@PathVariable Long id) {
        return R.success(tagsService.getById(id));
    }
    //修改
    @PutMapping
    public R update(@RequestBody Tags tags){
        boolean b = tagsService.updateById(tags);
        return b?R.success("修改成功"):R.error("修改失败");
    }
    //删除标签
    @DeleteMapping
    public R delete(@RequestParam Long id){
        boolean b = tagsService.removeById(id);
        return b?R.success("删除成功"):R.error("删除失败");
    }
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping
    public R find()
    {
        //1.根据key去redis中查询
        Object tagslist = redisTemplate.opsForValue().get("tagslist");
        List<Tags> list = new ArrayList<>();
        if(!StringUtils.isEmpty(tagslist)){
            list=(List<Tags>) tagslist;
        }else{
            list = tagsService.list();
            //放入redis
           redisTemplate.opsForValue().set("tagslist",list);
        }
        return R.success(tagsService.list());
    }
}
